package fast_slow_pointers;

import Node.ListNode;

public class RemoveDuplicates {

    /**
     * 数组去重
     * @param nums
     * @return
     */
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int slow = 0, fast = 0;
        while (fast < nums.length) {
            if (nums[fast] != nums[slow]) {
                slow++;
                // 维护nums[0...slow]无重复
                nums[slow] = nums[fast];
            }
            fast++;
        }

        // 数组长度为索引 +１
        return slow + 1;
    }

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null)
            return null;
        ListNode slow = head, fast = head;
        while (fast != null) {
            if (fast.val != slow.val) {
                slow.next = fast;
                slow = slow.next;
            }
            fast = fast.next;
        }

        // 断开与后面重复元素的链接
        slow.next = null;
        return head;
    }
}
